public class TotalNQueens {

    public int totalNQueens(int n) {
        int[] nums = new int[n];
        return process(nums, 0, n);
    }

    public int process(int[] nums, int i, int n) {
        if (i == n) {
            return 1;
        }
        int ans = 0;
        for (int j = 0; j < n; j++) {
            if (isValid(nums, i, j)) {
                nums[i] = j;
                ans += process(nums, i + 1, n);
            }
        }
        return ans;
    }

    public boolean isValid(int[] nums, int i, int j) {
        for (int k = 0; k < i; k++) {
            if (j == nums[k] || Math.abs(nums[k] - j) == Math.abs(i - k)) {
                return false;
            }
        }
        return true;
    }
}
